package com.adingxiong.pm.config;


import com.adingxiong.pm.model.RetCode;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.builders.*;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.service.Parameter;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * SwaggerUI的配置类
 */

@Configuration        //配置类特有注解
@EnableSwagger2    //自动配置
public class SwaggerConfig {
    @Bean
    public Docket createRestApi(){
        //添加全局状态码显示
        List<ResponseMessage> responseMessages = new ArrayList<>();
        Arrays.stream(RetCode.values()).forEach(retCode -> {
            responseMessages.add(new ResponseMessageBuilder().code(retCode.getCode()).message(retCode.getMsg()).responseModel(
                    new ModelRef(retCode.getMsg())).build());
        });

        return new Docket(DocumentationType.SWAGGER_2)
                .globalResponseMessage(RequestMethod.GET, responseMessages)
                .globalResponseMessage(RequestMethod.POST, responseMessages)
                .globalResponseMessage(RequestMethod.PUT, responseMessages)
                .globalResponseMessage(RequestMethod.DELETE, responseMessages)
                .apiInfo(apiInfo())
                .useDefaultResponseMessages(false)
                .globalOperationParameters(globalOperationParam())//全局参数
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.regex("/.*")) //监控所有的路径
                .build();
    }


    private List<Parameter> globalOperationParam(){
        ParameterBuilder builder = new ParameterBuilder();
        Parameter parameter = builder.name("tokenHeader").description("登录接口返回的token")
                .modelRef(new ModelRef("String"))
                .parameterType("header")
                .required(false).build();
        ArrayList<Parameter> list = new ArrayList<>();
        list.add(parameter);
        return list;
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("后台管理系统Restful Api接口说明")
                .description("这里配置公司信息")
                .termsOfServiceUrl("这里是项目的访问Url地址")
                .contact(new Contact("adiongx" ,null , "1374543195@qq.com"))
                .version("1.0")
                .build();
    }

}
